<template>
    <div class="arcgis">
        <div id="viewDiv" class="viewDiv">
            <div class="loading" v-if="loadSuccess">
                <img src="/src/assets/loading.gif" alt="">
            </div>
        </div>
        <div class="leftBox" :style="{left: `${isShowLeftBox ? leftBoxOffset : '-25%'}`}">
            <div class="jvxx">
                <zlc-box title="基本信息">
                    <template #default>
                        <div class="content">
                            <base-msg :data="baseMsgData" v-if="grade == 0"></base-msg>

                            <base-mes-bureau v-else :data="baseMsgData"> </base-mes-bureau>

                        </div>
                    </template>
                </zlc-box>
            </div>
            <div class="zcxmgl">
                <zlc-box title="项目立项管理">
                    <template #default>
                        <asset-project-manage v-if="grade == 0" ref="baseItemCom" btn-text="查看" field="projectName" :datas="baseItem" @change="addBaseItem" @position="changeBaseType" @details="changeRightFn"></asset-project-manage>
                        <project-statistics v-else></project-statistics>
                    </template>
                </zlc-box>
            </div>
            <div class="tdqkpm">
                <zlc-box title="基地照片" :data-scroll="true" v-if="grade == 0">
                    <template #default>
                        <land-rank :datas="baseData.basePhoto"></land-rank>
                    </template>
                </zlc-box>
                <zlc-box title="占地面积统计" :data-scroll="true" v-else>
                    <template #default>
                        <land-area-statistics :data="landAreaStatistics"></land-area-statistics>
                    </template>
                </zlc-box>

            </div>
        </div>
        <div class="rightBox" :style="{right: `${isShowRightBox ? RightBoxOffset : '-25%'}`}">
            <template v-if="!isShowRightDetails">
                <container :data="baseData"></container>
<!--                <div class="kptj grid">-->

<!--                    &lt;!&ndash;                    基地级&ndash;&gt;-->
<!--                    <zlc-box title="监控管理" v-if="grade == 0">-->
<!--                        <template #default>-->
<!--                            <div class="main">-->
<!--                                <evaluation-statistics ref="monitorCom" btn-text="定位" field="monitorName" :datas="monitorDatas" @change="addMonitor" @position="mapGoTo"></evaluation-statistics>-->
<!--                            </div>-->
<!--                        </template>-->
<!--                    </zlc-box>-->
<!--                    &lt;!&ndash;                    局级&ndash;&gt;-->
<!--                    <zlc-box title="基地使用情况" v-else>-->
<!--                        <template #default>-->
<!--                            <div class="main">-->
<!--                                <base-usage :data="baseMsgData"></base-usage>-->
<!--                            </div>-->
<!--                        </template>-->
<!--                    </zlc-box>-->

<!--                </div>-->
<!--                <div class="jdsl grid">-->

<!--                    &lt;!&ndash;         所 等级       &ndash;&gt;-->
<!--                    <zlc-box title="建筑楼房" v-if="grade == 0">-->
<!--                        <template #default>-->
<!--                            <div class="chat">-->
<!--                                <patrol-count ref="patrolCountCom" :data="patrolCountData" @addBuildings="addBuildings"></patrol-count>-->
<!--                            </div>-->
<!--                        </template>-->
<!--                    </zlc-box>-->
<!--                    &lt;!&ndash;        局 等级        &ndash;&gt;-->
<!--                    <zlc-box title="基地分布情况" v-else>-->
<!--                        <template #default>-->
<!--                            <base-count :data="baseCount"></base-count>-->
<!--                        </template>-->
<!--                    </zlc-box>-->
<!--                </div>-->
<!--                <div class="whtj grid">-->

<!--                    &lt;!&ndash;               基地 等级 &ndash;&gt;-->
<!--                    <zlc-box title="土地价值" v-if="grade == 0">-->
<!--                        <template #default>-->
<!--                            <div class="chat">-->
<!--                                <maintenance-count :data="maintenanceCountData"></maintenance-count>-->
<!--                            </div>-->
<!--                        </template>-->
<!--                    </zlc-box>-->
<!--                    &lt;!&ndash;                局 等级&ndash;&gt;-->
<!--                    <zlc-box title="独立房产统计" v-else>-->
<!--                        <template #default>-->
<!--                            <land-value :data="IndependentProperty"></land-value>-->
<!--                        </template>-->
<!--                    </zlc-box>-->
<!--                </div>-->
            </template>

            <template v-else>
                <!--    详情-->
                <div class="Details">
                    <div class="closeDetails" @click="cancelDetails">
                        <img src="/src/assets/closeDetails.png" class="close" alt="">
                    </div>
                    <RightDetails ref="rightDetails" @openItemModal="openItemModal"></RightDetails>
                </div>
            </template>
        </div>
        <div class="leftbar">
            <div class="lt"></div>
            <div class="lb"></div>
            <div class="rt"></div>
            <div class="rb"></div>
            <button
                class="action-button esri-icon-measure-line"
                id="distanceButton"
                type="button"
                title="测量距离"
                @click="countLength"
            >

                <img src="/src/assets/distance.png" alt="" class="icon">
            </button>
            <button
                class="action-button esri-icon-measure-area"
                id="areaButton"
                type="button"
                title="测量面积"
                @click="countArea"
            >
                <img src="/src/assets/area.png" alt="" class="icon">
            </button>
            <button
                class="action-button"
                id="backBase"
                type="button"
                title="回到基地"
                @click="backBase"
            >
                <img src="/src/assets/position.png" alt="" class="icon">
            </button>

            <button
                class="action-button"
                type="button"
                title="全屏模式"
                @click="fullScreen"
            >
                <img src="/src/assets/fullScreen.png" alt="" class="icon">
            </button>

            <button
                class="action-button"
                type="button"
                title="地形开关"
                @click="gaocheng"
            >
                <img src="/src/assets/gaocheng.png" alt="" class="icon">
            </button>
        </div>

        <zlc-project-details ref="projectDetailsCom" :datas="projectDetailsDatas"></zlc-project-details>
        <monitor-popup ref="monitorPopup"></monitor-popup>
        <zlc-base-item-popup :datas="baseItemDatas" ref="baseItemPopupCom"></zlc-base-item-popup>
        <zlc-building-popup ref="buildingPopupCom"></zlc-building-popup>
        <!--        查看详情子级内容 弹窗-->
        <viewDetailsItemModal ref="itemModal"></viewDetailsItemModal>

    </div>
</template>
<script>
import {ref, onMounted, reactive, toRefs, nextTick,watch } from "vue"
import RightDetails from './components/RightDetails.vue'
import ZlcBox from "../../components/zlcBox/zlcBox.vue";
import zlcChat from "../../components/zlcChat/zlcChat.vue";
import zlcProgress from "../../components/zlcProgress/zlcProgress.vue";
import monitorPopup from "../../components/monitorPopup/monitorPopup.vue"
import baseMsg from "./components/baseMsg.vue";
import maintenanceCount from "./components/maintenanceCount.vue";
import assetProjectManage from "./components/assetProjectManage.vue";
import landRank from "./components/landRank.vue";
import landValue from "./components/landValue.vue";
import zlcSelect from "../../components/zlcSelect/zlcSelect.vue";
import ZlcBaseItemPopup from "../../components/zlcBaseItemPopup/zlcBaseItemPopup.vue";
import ZlcProjectDetails from "../../components/zlcProjectDetails/zlcProjectDetails.vue";
import zlcBuildingPopup from "../../components/zlcBuildingPopup/zlcBuildingPopup.vue";
import baseMesBureau from "./components/baseMesBureau.vue";
import landAreaStatistics from "./components/landAreaStatistics.vue";
import {
    queryMonitor,
    queryBaseMes,
    queryBaeDetails,
    queryProjectDetails,
    queryBaeDetailsPlus,
    getIntegratedMeshLayerToken
} from "/src/api/api.js";
import Map from '@arcgis/core/Map.js';
import SceneView from '@arcgis/core/views/SceneView.js';
import WebTileLayer from "@arcgis/core/layers/WebTileLayer";
import DirectLineMeasurement3D from "@arcgis/core/widgets/DirectLineMeasurement3D.js";
import AreaMeasurement3D from "@arcgis/core/widgets/AreaMeasurement3D.js";
import * as promiseUtils from "@arcgis/core/core/promiseUtils.js";
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import IntegratedMeshLayer from "@arcgis/core/layers/IntegratedMeshLayer.js";
import Extent from "@arcgis/core/geometry/Extent.js";
import TileInfo from "@arcgis/core/layers/support/TileInfo.js";
import SpatialReference from "@arcgis/core/geometry/SpatialReference.js";
import LabelClass from "@arcgis/core/layers/support/LabelClass.js";
import { message } from 'ant-design-vue';
import LandAreaStatistics from "./components/landAreaStatistics.vue";
import ProjectStatistics from "./components/ProjectStatistics.vue";
import viewDetailsItemModal from '@/views/home/components/viewDetailsItemModal.vue'
import ElevationLayer from "@arcgis/core/layers/ElevationLayer.js";
import Container from "../../components/container/container.vue";
import esriId from "@arcgis/core/identity/IdentityManager.js";

import FillSymbol3DLayer from "@arcgis/core/symbols/FillSymbol3DLayer.js";
import MeshSymbol3D from "@arcgis/core/symbols/MeshSymbol3D.js";
import SimpleRenderer from "@arcgis/core/renderers/SimpleRenderer.js";
export default {
    name: "arcgis",
    components: {
        Container,
        ProjectStatistics,
        LandAreaStatistics,
        viewDetailsItemModal,
        RightDetails,
        zlcBuildingPopup,
        ZlcProjectDetails,
        ZlcBaseItemPopup,
        ZlcBox,
        zlcChat,
        zlcProgress,
        baseMsg,
        maintenanceCount,
        monitorPopup,
        assetProjectManage,
        landRank,
        landValue,
        zlcSelect,
        baseMesBureau,
        landAreaStatistics,
    },
    setup() {
        //局、所、队 - 等级
        let grade = window.typeStr

        //acrgis全局变量 - start
        window.viewer = null
        window.map = null
        window.highlight = null
        //高亮图层
        window.featureLayer = null
        let baseId = window.baseId//基地的id
        const spatialReference = new SpatialReference({
            wkid: 4490
        });
        //acrgis全局变量 - end

        //基地信息
        let baseData = ref({})
        //基地项目
        let baseItem = ref([])
        //加载中控制变量
        let loadSuccess = ref(false)
        //基本信息 - 数据
        let baseMsgData = ref({})



        //监控popup
        let monitorPopup = ref(null)
        //项目现状组件
        let projectDetailsCom = ref(null)
        //项目现状data
        let projectDetailsDatas = ref({})


        //资产项目组件
        let baseItemCom = ref(null)
        //查看项目详情
        let baseItemDatas = ref({})
        let baseItemPopupCom = ref(null)
        //楼房弹窗组件
        let buildingPopupCom = ref(null)
        let closeHeighLight = ref(true)
        //占地面积统计
        let landAreaStatistics = ref({})
        let activeWidget = null;


        //右侧数据大盒子 - 与详情盒子切换
        let containerCom = ref(null)

        //a serise of arcgis function - start

        //初始化地球
        let initArcGisMap = () => {


            var tiandituBaseUrl = "http://{subDomain}.tianditu.com"; //天地图服务地址
            let token = import.meta.env.VITE_APP_3DBASE_URL; //20532113fca1cb9c2cf4ed1c9b11c377


            let tileInfo = new TileInfo({
                dpi: window.devicePixelRatio * 96 ,
                rows: 256,
                cols: 256,
                compressionQuality: 0,
                origin: {
                    x: -180,
                    y: 90
                },
                spatialReference: spatialReference,
                lods: [
                    { level: 0, levelValue: 1, scale: 295829355.45, resolution: 0.703125 },
                    { level: 1, levelValue: 2, scale: 147914677.725, resolution: 0.3515625 },
                    { level: 2, levelValue: 3, scale: 73957338.8625, resolution: 0.17578125 },
                    { level: 3, levelValue: 4, scale: 36978669.43125, resolution: 0.087890625 },
                    { level: 4, levelValue: 5, scale: 18489334.715625, resolution: 0.0439453125 },
                    { level: 5, levelValue: 6, scale: 9244667.3578125, resolution: 0.02197265625 },
                    { level: 6, levelValue: 7, scale: 4622333.67890625, resolution: 0.010986328125 },
                    { level: 7, levelValue: 8, scale: 2311166.839453125, resolution: 0.0054931640625 },
                    { level: 8, levelValue: 9, scale: 1155583.4197265625, resolution: 0.00274658203125 },
                    { level: 9, levelValue: 10, scale: 577791.7098632812, resolution: 0.001373291015625 },
                    { level: 10, levelValue: 11, scale: 288895.8549316406, resolution: 0.0006866455078125 },
                    { level: 11, levelValue: 12, scale: 144447.9274658203, resolution: 0.00034332275390625 },
                    { level: 12, levelValue: 13, scale: 72223.96373291015, resolution: 0.000171661376953125 },
                    { level: 13, levelValue: 14, scale: 36111.98186645508, resolution: 0.0000858306884765625 },
                    { level: 14, levelValue: 15, scale: 18055.99093322754, resolution: 0.00004291534423828125 },
                    { level: 15, levelValue: 16, scale: 9027.99546661377, resolution: 0.000021457672119140625 },
                    { level: 16, levelValue: 17, scale: 4513.997733306885, resolution: 0.000010728836059570312 },
                    { level: 17, levelValue: 18, scale: 2256.9988666534423, resolution: 0.000005364418029785156 },
                    { level: 18, levelValue: 19, scale: 1128.4994333267211, resolution: 0.000002682209014892578 },
                    // { level: 19, levelValue: 20, scale: 564.2497166633606, resolution: 0.000001341104507446289 },
                    // { level: 20, levelValue: 21, scale: 282.1248583316803, resolution: 0.0000006705522537231445 },
                    // { level: 21, levelValue: 22, scale: 141.0624291658401, resolution: 0.00000033527612686157225 },
                    // { level: 22, levelValue: 23, scale: 70.53121458292006, resolution: 0.0000006705522537231445 },
                    // { level: 23, levelValue: 24, scale: 35.26560729146003, resolution: 0.00000033527612686157225 }
                ],
                maxZoom: 18,
                minZoom: 3,
            });

            //2.2 定义地图的extent
            const fullExtent = new Extent(-180, -90, 180, 90, spatialReference);
            const tdtyxlayer = new WebTileLayer({ // 天地图影像地图
                id: "test",
                title: "天地图影像地图",
                // urlTemplate: "http://{subDomain}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=" + token,
                urlTemplate: "http://{subDomain}.tianditu.gov.cn/img_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&tk="+token,
                subDomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
                fullExtent: fullExtent,
                tileInfo,
                copyright: '天地图',
                spatialReference: spatialReference
            });
            const tdtzjlayer = new WebTileLayer({ // 天地图影像注记
                id: "test",
                title: "天地图影像注记",
                urlTemplate: 'http://{subDomain}.tianditu.gov.cn/cia_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&tk='+token,
                subDomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
                fullExtent: fullExtent,
                tileInfo,
                copyright: '天地图',
                spatialReference: spatialReference
            });

            window.map = new Map({
                basemap: {
                    baseLayers: [tdtyxlayer, tdtzjlayer]
                }
            });




            let lodsView = [
                { level: 0, levelValue: 1, scale: 295829355.45, resolution: 0.703125 },
                { level: 1, levelValue: 2, scale: 147914677.725, resolution: 0.3515625 },
                { level: 2, levelValue: 3, scale: 73957338.8625, resolution: 0.17578125 },
                { level: 3, levelValue: 4, scale: 36978669.43125, resolution: 0.087890625 },
                { level: 4, levelValue: 5, scale: 18489334.715625, resolution: 0.0439453125 },
                { level: 5, levelValue: 6, scale: 9244667.3578125, resolution: 0.02197265625 },
                { level: 6, levelValue: 7, scale: 4622333.67890625, resolution: 0.010986328125 },
                { level: 7, levelValue: 8, scale: 2311166.839453125, resolution: 0.0054931640625 },
                { level: 8, levelValue: 9, scale: 1155583.4197265625, resolution: 0.00274658203125 },
                { level: 9, levelValue: 10, scale: 577791.7098632812, resolution: 0.001373291015625 },
                { level: 10, levelValue: 11, scale: 288895.8549316406, resolution: 0.0006866455078125 },
                { level: 11, levelValue: 12, scale: 144447.9274658203, resolution: 0.00034332275390625 },
                { level: 12, levelValue: 13, scale: 72223.96373291015, resolution: 0.000171661376953125 },
                { level: 13, levelValue: 14, scale: 36111.98186645508, resolution: 0.0000858306884765625 },
                { level: 14, levelValue: 15, scale: 18055.99093322754, resolution: 0.00004291534423828125 },
                { level: 15, levelValue: 16, scale: 9027.99546661377, resolution: 0.000021457672119140625 },
                { level: 16, levelValue: 17, scale: 4513.997733306885, resolution: 0.000010728836059570312 },
                { level: 17, levelValue: 18, scale: 2256.9988666534423, resolution: 0.000005364418029785156 },
                { level: 18, levelValue: 19, scale: 1128.4994333267211, resolution: 0.000002682209014892578 },
                { level: 19, levelValue: 20, scale: 564.2497166633606, resolution: 0.000001341104507446289 },
                { level: 20, levelValue: 21, scale: 282.1248583316803, resolution: 0.0000006705522537231445 },
                { level: 21, levelValue: 22, scale: 141.0624291658401, resolution: 0.00000033527612686157225 },
                { level: 22, levelValue: 23, scale: 70.53121458292006, resolution: 0.0000006705522537231445 },
                { level: 23, levelValue: 24, scale: 35.26560729146003, resolution: 0.00000033527612686157225 }
            ]
            window.viewer = new SceneView({ //SceneView
                container: "viewDiv",
                map: window.map,
                zoom: 18,
                constraints: {
                    lods: lodsView,
                    minZoom: 3,
                    maxZoom: 23
                },

                // highlightOptions: {
                //     color: [255, 0, 0, 0.5],
                //     haloColor: "red",
                //     haloOpacity: 0.9,
                //     fillOpacity: 0.2,
                //     shadowColor: "red",
                //     shadowOpacity: 0.5
                // },
            });

            // 1、添加房屋方法
            getToken().then(res => {

                esriId.registerToken({
                    expires: 1000 * 60 * 60 * 12 * 7,
                    server: "https://ag.jxdkchy.com/server/rest/services/dem4490_WEL/ImageServer", //
                    token: res,
                    ssl: true
                })


                if(window['3DbaseUrl'] == 'null'){
                    message.warning({
                        content: () => '暂无模型数据',
                        style: {
                            marginTop: '20vh',
                        },
                        duration: 5
                    })
                    return
                }

                const sceneLayer = new IntegratedMeshLayer({
                    url: window['3DbaseUrl'],//"https://ag.jxdkchy.com/server/rest/services/Hosted/hddyt2000_WSL1/SceneServer",
                    apiKey: res,
                    title: "倾斜摄影",
                    spatialReference: spatialReference,
                    elevationInfo: {
                        mode: 'absolute-height', // 将倾斜摄影贴着底图
                        // offset: -40 //window['modelHeight'] == 0 ? -40 : window['modelHeight']
                    },
                    id: 'IntegratedMeshLayer'
                });



                window.map.add(sceneLayer);
                //相机视角移动至房屋
                sceneLayer.when(() => {
                    window.viewer.goTo({
                        target: sceneLayer.fullExtent,
                        zoom: 18,
                        // heading: 45,
                        tilt: 45  // 设置相机的倾斜角度，以度为单位
                    },{
                        duration: 1500
                    })
                })

                //添加点击事件
                window.viewer.whenLayerView(sceneLayer).then((layerView) => {
                    let that = this
                    //房屋数据加载完成
                    loadSuccess.value = false

                    window.viewer.on('click', (event) => {
                        event.stopPropagation() //配合方法二弹出popup使用(推荐)，使用方式一请注释
                        window.viewer.hitTest(event).then((response) => {
                            if (response.results.length == 0) return
                            const graphic = response.results[0]?.graphic;
                            if(graphic.attributes.type == 'monitor'){
                                //点击了监控
                                monitorPopup.value.onshow({title:graphic.attributes.name_text, videoUrl:graphic.attributes.monitorSrc})
                            }else if(graphic.attributes.type == 'projectDetails'){
                                projectDetailsCom.value.showModel()
                                projectDetailsDatas.value = graphic.attributes
                            }else if(graphic.attributes.type == 'building'){

                                let { id, name_text } = graphic.attributes

                                buildingPopupCom.value.showModel(id, name_text)


                                //弹窗 - 方法一：第一次popup出现的位置不对，需拖动或者缩放地球恢复，此后都正常
                                // let mapPoint = event.mapPoint
                                // // viewer.popup.autoOpenEnabled = false  //废除
                                //     let node = document.getElementById('viewDiv')
                                //     let instance = createVNode(Popup, {
                                //         name: graphic.attributes.OBJECTID,
                                //         onClose: (event) => {
                                //             viewer.closePopup()
                                //         }
                                //     })
                                //
                                // instance.appContext = createApp({})._context
                                // render(instance, node)
                                // const hide = message.loading('信息查找中...', 0);
                                // setTimeout(() => {
                                //     hide()
                                //     viewer.openPopup({
                                //         title: '子组件',
                                //         location: mapPoint,
                                //         content: instance.el
                                //     })
                                // }, 2000);

                                //弹窗 - 方法二：
                                // let screenPoint = viewer.toScreen(event.mapPoint);
                                // popupPosition.value = screenPoint
                                //
                                // viewer.watch('center', () => {
                                //     let screenPoint = viewer.toScreen(event.mapPoint);
                                //     popupPosition.value = screenPoint
                                // })
                                //
                                // if(showPopup.value) return
                                // showPopup.value= true


                                // window.addEventListener('resize', () => {
                                //     let screenPoint = viewer.toScreen(event.mapPoint);
                                //     popupPosition.value = screenPoint
                                // })


                            }else{
                                let { id, name } = graphic.attributes
                                buildingPopupCom.value.showModel(id, name)
                            }
                        });
                    });
                    // window.viewer.on('pointer-move', (event) => {
                    //     window.viewer.hitTest(event).then((response) => {
                    //         if(response.results.length == 0){
                    //             // closeHeighLight.value = true
                    //             return
                    //         }
                    //         const graphic = response.results[0]?.graphic;
                    //         if(graphic.attributes.type == 'baimo'){
                    //             window.viewer.whenLayerView(window.featureLayer).then((layerView) => {
                    //                 // closeHeighLight.value = false
                    //                 window.viewer.hitTest(event).then((response) => {
                    //
                    //                     if(response.results.length == 0){
                    //                         return
                    //                     }
                    //                     const graphic = response.results[0]?.graphic;
                    //                     let { longitudeLatitude } = graphic.attributes
                    //
                    //                     if(graphic.attributes.type != "baimo") return
                    //
                    //                     const colorRenderer = {
                    //                         type: 'unique-value', // 唯一值渲染
                    //                         field: 'id', // 根据省份字段
                    //                         uniqueValueInfos: [
                    //                             {
                    //                                 value: graphic.attributes.id,
                    //                                 symbol: {
                    //                                     type: 'polygon-3d',
                    //                                     symbolLayers: [{
                    //                                         type: 'extrude',
                    //                                         size: 20, //longitudeLatitude.split(",")[2], // 白膜的高度，可以根据需要调整
                    //                                         material: {
                    //                                             color: [0, 255, 255, 0.1] // 白膜的颜色，可以根据需要调整
                    //                                         }
                    //                                     }]
                    //                                 }
                    //                             }
                    //                         ],
                    //                         defaultSymbol: {
                    //                             type: "simple-fill",
                    //                             color: 'rgba(0, 0, 0, 0)', // 设置填充颜色和透明度
                    //                             outline: {
                    //                                 color: [0, 0, 0, 0], // 设置边界线颜色和透明度
                    //                                 width: 1, // 设置边界线宽度
                    //                             }
                    //                         }
                    //                     };
                    //
                    //                     // 将渲染器应用于 GeoJSONLayer
                    //                     window.featureLayer.renderer = colorRenderer;
                    //                     window.viewer.whenLayerView(graphic.layer).then(function(lv){
                    //                         window.highlight = lv.highlight(graphic)
                    //                         // closeHeighLight.value = false
                    //                     })
                    //                 })
                    //             })
                    //         }
                    //
                    //     })
                    // })
                })
            })


            window.viewer.ui.components = []
        }

        //a serise of arcgis function - start

        let removeHeighLight = () => {
            window.highlight && window.highlight.remove() //清除上一次的
            window.highlight = null
            const colorRenderer = {
                type: 'unique-value', // 唯一值渲染
                field: 'id', // 根据省份字段
                // uniqueValueInfos: [
                //     {
                //         value: graphic.attributes.id,
                //         symbol: {
                //             type: 'polygon-3d',
                //             symbolLayers: [{
                //                 type: 'extrude',
                //                 size: longitudeLatitude.split(",")[2], // 白膜的高度，可以根据需要调整
                //                 material: {
                //                     color: [0, 255, 255, 0.1] // 白膜的颜色，可以根据需要调整
                //                 }
                //             }]
                //         }
                //     }
                // ],
                defaultSymbol: {
                    type: "simple-fill",
                    color: 'rgba(0, 0, 0, 0.1)', // 设置填充颜色和透明度
                    outline: {
                        color: [0, 0, 0, 0.1], // 设置边界线颜色和透明度
                        width: 1, // 设置边界线宽度
                    }
                }
            };

            // 将渲染器应用于 GeoJSONLayer
            window.featureLayer.renderer = colorRenderer;
        }

        //获取房屋数据的token
        let getToken = () => {
            return new Promise((resolve, reject) => {
                getIntegratedMeshLayerToken().then(res => {
                    resolve(JSON.parse(res.message).token)
                })
            })

        }

        //初始化，拆线呢基地信息
        let init = () => {
            let typeStr = window.typeStr

            if(typeStr == 0) {
                //基地信息
                queryBaeDetails({id:baseId }).then(res => {
                    baseData.value = res.result
                    let {
                        area,
                        population,
                        buildingsTotal,
                        households,
                        landEvaluate,
                        landCost,
                        structurePublicPf,
                        structurePublicLf,
                        structurePrivatePf,
                        structurePrivateLf
                    } = res.result
                    baseMsgData.value = {
                        area, //占地面积
                        population, //住户人数
                        buildingsTotal, //土地评估价值
                        households //住户数
                    }


                })

                //基地下的项目
                queryBaseMes({ baseId: baseId }).then(res => {
                    baseItem.value = res.result.records.map(item => {
                        item.zlcName = item.projectName + "(" + item.year + '年' + item.auditType_dictText + ")"
                        item.zlcShow = false
                        return item
                    })
                })
            }else {
                let sysOrgCode = window.sysOrgCode
                queryBaeDetailsPlus({ superQueryParams: JSON.stringify([{ field:"sysOrgCode", rule:"right_like", val: sysOrgCode}]) }).then(res => {
                    let { dpBaseAreaInfo, dpBaseDistribution, dpBaseInfo, dpIndependentHouseDistribution } = res.result
                    baseMsgData.value = dpBaseInfo
                    landAreaStatistics.value = dpBaseAreaInfo

                })
            }

        }

        let setActiveWidget = type => {
            switch (type) {
                case "distance":
                    activeWidget = new DirectLineMeasurement3D({
                        view: window.viewer
                    });

                    // skip the initial 'new measurement' button
                    activeWidget.viewModel.start().catch((error) => {
                        if (promiseUtils.isAbortError(error)) {
                            return; // don't display abort errors
                        }
                        throw error; // throw other errors since they are of interest
                    });

                    window.viewer.ui.add(activeWidget, "top-right");
                    setActiveButton(document.getElementById("distanceButton"));
                    break;
                case "area":
                    activeWidget = new AreaMeasurement3D({
                        view: window.viewer
                    });

                    // skip the initial 'new measurement' button
                    activeWidget.viewModel.start().catch((error) => {
                        if (promiseUtils.isAbortError(error)) {
                            return; // don't display abort errors
                        }
                        throw error; // throw other errors since they are of interest
                    });

                    window.viewer.ui.add(activeWidget, "top-right");
                    setActiveButton(document.getElementById("areaButton"));
                    break;
                case null:
                    if (activeWidget) {
                        window.viewer.ui.remove(activeWidget);
                        activeWidget.destroy();
                        activeWidget = null;
                    }
                    break;
            }
        }

        let setActiveButton = selectedButton => {
            // focus the view to activate keyboard shortcuts for sketching
            window.viewer.focus();
            const elements = document.getElementsByClassName("active");
            for (let i = 0; i < elements.length; i++) {
                elements[i].classList.remove("active");
            }
            if (selectedButton) {
                selectedButton.classList.add("active");

            }
        }

        //测量距离
        let countLength = event => {
            //添加测距离和面积算法
            // event.stopPropagation();
            setActiveWidget(null); //每次点击 - 初始化UI组件
            if (!document.getElementById('distanceButton').classList.contains("active")) { //没有active名
                setActiveWidget("distance");
            } else { //有active名
                setActiveButton(null);
            }

        }
        //回到基地
        let backBase = () => {
            window.map.layers.forEach(layer => {
                window.viewer.goTo({
                    target: layer.fullExtent,
                    zoom: 18,
                    // heading: 45,
                    tilt: 45  // 设置相机的倾斜角度，以度为单位
                },{
                    duration: 1500
                })
            });

        }

        //全屏模式
        let fullScreen = () => {
            leftContentObj.isShowLeftBox = !leftContentObj.isShowLeftBox
            contentObj.isShowRightBox = !contentObj.isShowRightBox
        }

        //地形开关
        let gaocheng = () => {
            let foundLayer = window.map.findLayerById("elevationLayer");
            if(foundLayer){
                foundLayer.visible = !foundLayer.visible

            }else{
                //加载三维地形
                const elevationLayer = new ElevationLayer({
                    url:"https://ag.jxdkchy.com/server/rest/services/dem4490_WEL/ImageServer",
                    // apiKey: res,
                    // agstoken:res,
                    // Token:res,
                    spatialReference: spatialReference,
                    visible: true,
                    id: 'elevationLayer'
                });

                // add the elevationlayer after the ground instance got created
                window.map.ground.when(() => {
                    window.map.ground.layers.add(elevationLayer);
                });
            }
        }

        //测量面积
        let countArea = () => {
            setActiveWidget(null);
            if (!document.getElementById('areaButton').classList.contains("active")) {
                setActiveWidget("area");
            } else {
                setActiveButton(null);
            }
        }


        //添加基地项目
        let addBaseItem = (type) => {

            let ids = baseItem.value.map(i => {
                return i.id
            })

            let has = window.map.layers.items.filter(item => ids.includes(item.id))

            if(has.length){
                has.forEach( i => {
                    if(type){
                        i.visible = false
                    }else{
                        i.visible = !i.visible
                    }
                })
                // setTimeout(() => {
                //     baseItemCom.value.hidden()
                // }, 1000)
                return
            }else{
                let promiseArr = []
                ids.forEach(i => {
                    promiseArr.push(
                        changeBaseType(i)
                    )
                })

                Promise.all(promiseArr).then(res => {
                    baseItemCom.value.showAll()
                })
            }


        }


        let ggp = new URL("@assets/buildingIcon.png", import.meta.url).href;
        const iconSymbol = {
            type: "point-3d",
            symbolLayers: [
                {
                    type: "icon",
                    resource: { href: ggp }, //https://www.jxdkchy.com:30340/src/sxt.png
                    size: 40
                }
            ],
            verticalOffset: {
                screenLength: 20, // 调整垂直偏移量
            },
        };
        const iconSymbolRenderer = {
            type: "simple",
            symbol: iconSymbol
        };
        const labelClass = new LabelClass({
            symbol: {
                type: "text",
                color: "#fff",
                backgroundColor: [0, 0, 0, 0.5],
                font: {
                    size: 14,
                    // weight: "bold"
                },
            },
            labelPlacement: "above-center",
            labelExpressionInfo: {
                expression: '$feature.zlcName' //"$feature.name_text" + `\n`
            }
        })
        let changeBaseType = (id, type, itemArr) => {


            //隐藏其他项目icon
            itemArr.forEach(i => {
                if(!i.zlcShow){
                    let noNow = window.map.layers.items.filter(item => item.id == i.id)
                    if(noNow.length){
                        noNow.forEach(it => {
                            it.visible = false
                        })
                        return
                    }
                }else{
                    let has = window.map.layers.items.find(item => item.id == i.id)
                    if(has){
                        has.visible = true
                        return
                    }else{
                        addNewBuildingIcon()
                    }
                }
            })

            // let pictureSymbol = new PictureMarkerSymbol({
            //     url: "/src/assets/1.png", // 替换为图标图片的路径
            //     width: '150px',
            //     height: '10px',
            //     // yoffset: 10,
            //     // xoffset: 75
            // });
            //
            // const iconSymbolRenderer = {
            //     type: "simple", //
            //     symbol: pictureSymbol
            // };
            // const labelClass = new LabelClass({
            //     symbol: {
            //         type: "text",
            //         color: "#fff",
            //         // backgroundColor: [0, 0, 0, 0.5],
            //         font: {
            //             size: 10,
            //             // weight: "bold"
            //         },
            //     },
            //     labelPlacement: "center-center",
            //     labelExpressionInfo: {
            //         expression: '"姓名：" + $feature.name_text +\n"\\n" +\n"\\n"+\n"\\n"'//"$feature.name_text" + `\n`
            //     }
            // })

            if(!type) return
            function addNewBuildingIcon(){
                return new Promise((resolve, reject) => {
                    const hide = message.loading('点位渲染中...', 0);

                    queryProjectDetails({ assetItemId: id, baseId: baseId }).then(res => {
                        resolve()
                        setTimeout(hide, 1000)
                        if(res.result.records.length == 0) return
                        let graphicsLayerArr = new FeatureLayer({
                            id: id,
                            source: res.result.records.map((item, index) => {
                                return {
                                    geometry: {
                                        type: "point",
                                        longitude: item.longitudeLatitude.split(',')[0],
                                        latitude: item.longitudeLatitude.split(',')[1],
                                        z: item.longitudeLatitude.split(',')[2]
                                    },
                                    attributes: Object.assign(item,{type: 'projectDetails', zlcName: item.name.length < 12 ? item.name : item.name.substr(0, 12) + '...'})
                                }
                            }),
                            fields: [ //这里是attributes中所有的属性配置，就是定义什么类型、别名
                                {
                                    name: "id",
                                    alias: "id",
                                    type: "oid"
                                },
                                {
                                    name: "type",
                                    alias: "type",
                                    type: "string"
                                },
                                {
                                    name: "zlcName",
                                    alias: "zlcName",
                                    type: "string"
                                },
                                {
                                    name: "assetsUrl",
                                    alias: "assetsUrl",
                                    type: "string"
                                },
                                {
                                    name: "attachments",
                                    alias: "attachments",
                                    type: "string"
                                },
                                {
                                    name: "details",
                                    alias: "details",
                                    type: "string"
                                }
                            ],
                            objectIdField: "id",
                            renderer: iconSymbolRenderer,
                            outFields: ["*"], //将attributes中的属性全部抛出，或者你抛出你想要的
                            labelingInfo: [labelClass]
                        })

                        window.map.add(graphicsLayerArr);
                    })
                })
            }






            // let has = map.layers.items.find(item => item.id == 'ProjectDetails')
            // if(has){
            //     has.visible = !has.visible
            //     return
            // }
            // queryProjectDetails({ assetItemId: id }).then(res => {
            //     console.log("项目明细", res)
            //     // let graphicsLayerArr = new FeatureLayer({
            //     //     id: "ProjectDetails",
            //     //     source: res.result.records.map(item => {
            //     //         return {
            //     //             geometry: {
            //     //                 type: "point",
            //     //                 longitude: item.longitude,
            //     //                 latitude: item.latitude,
            //     //                 z: item.height
            //     //             },
            //     //             attributes: {
            //     //                 id: item.id,
            //     //                 type: 'ProjectDetails',
            //     //                 name_text: item.monitorName,
            //     //                 monitorSrc: item.monitorSrc
            //     //             }
            //     //         }
            //     //     }),
            //     //     fields: [ //这里是attributes中所有的属性配置，就是定义什么类型、别名
            //     //         {
            //     //             name: "id",
            //     //             alias: "id",
            //     //             type: "oid"
            //     //         },
            //     //         {
            //     //             name: "type",
            //     //             alias: "type",
            //     //             type: "string"
            //     //         },
            //     //         {
            //     //             name: "name_text",
            //     //             alias: "name_text",
            //     //             type: "string"
            //     //         },
            //     //         {
            //     //             name: "monitorSrc",
            //     //             alias: "monitorSrc",
            //     //             type: "string"
            //     //         },
            //     //
            //     //     ],
            //     //     objectIdField: "id",
            //     //     renderer: iconSymbolRenderer,
            //     //     outFields: ["*"], //将attributes中的属性全部抛出，或者你抛出你想要的
            //     //     labelingInfo: [labelClass]
            //     // })
            //     //
            //     // map.add(graphicsLayerArr);
            // })
        }

        //项目详情
        let projectDetails = (index) => {
            baseItemDatas.value = baseItem.value[index]
            baseItemPopupCom.value.showModel()
        }



        watch(closeHeighLight, (newVal) => {
            // if(newVal) removeHeighLight()

        })



        onMounted(() => {
            init()
            initArcGisMap()
        })

        let contentObj = reactive({//左右容器相关的变量以及方法
            RightBoxOffset:'20px',//右侧盒子的偏移量
            RightSetTimeout:null, // 右侧展开收起的定时器
            isShowRightBox:true,//是否显示右侧
            isShowRightDetails:false,//当前是否显示右侧详情
            rightDetails:null,//右侧详情组件refs
            itemModal:null,//展示查看详情子级组件refs
            changeRightFn:(item)=>{//切换右侧详情
                if(contentObj.rightDetails ){//如果当前点击的详情为现在展示的详情，则不做任何操作
                    if(contentObj.rightDetails.DetailsObj.id === item.id) return
                }
                if(contentObj.RightSetTimeout) return
                if(contentObj.RightSetTimeout === null){
                    contentObj.isShowRightBox = !contentObj.isShowRightBox
                    contentObj.RightSetTimeout = setTimeout(()=>{
                        contentObj.isShowRightDetails = true
                        contentObj.isShowRightBox = !contentObj.isShowRightBox
                        contentObj.RightSetTimeout = null
                        nextTick(()=>{
                            contentObj.rightDetails.init(item)
                        })
                    },750)
                }
            },
            //关闭右侧查看详情 切换会原本的页面
            cancelDetails:()=>{
                contentObj.isShowRightBox = !contentObj.isShowRightBox

                setTimeout(()=>{
                    contentObj.isShowRightBox = !contentObj.isShowRightBox
                    contentObj.isShowRightDetails = false
                },750)
            },

            openItemModal(itemInfo){
                // console.log(itemInfo,'itemInfo')
                contentObj.itemModal.openModal(itemInfo)
            }

        })
        let leftContentObj = reactive({
            isShowLeftBox: true,
            leftBoxOffset:'20px',//左侧盒子的偏移量
        })
        return {
            ...toRefs(contentObj),
            ...toRefs(leftContentObj),
            grade,
            baseMsgData,
            baseData,
            baseItem,
            initArcGisMap,
            init,
            loadSuccess,
            setActiveWidget,
            setActiveButton,
            countLength,
            countArea,
            backBase,
            fullScreen,
            gaocheng,
            monitorPopup,
            projectDetailsCom,
            projectDetailsDatas,
            landAreaStatistics,
            baseItemCom,
            baseItemDatas,
            baseItemPopupCom,
            buildingPopupCom,
            addBaseItem,
            changeBaseType,
            projectDetails,
            containerCom
        }
    }
}
</script>

<style scoped lang="less">

.arcgis{
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    .viewDiv{
        width: 100%;
        height: 100%;
        & :deep(.esri-view-root){
            width: 100%;
            height: 100%;
            .esri-view-surface{
                width: 100%;
                height: 100%;
            }
        }
    }
    .leftBox{
        transition: 0.75s left ease-in-out;
        width: 23%;
        height: 87%;
        position: absolute;
        //top: 50%;
        //transform: translateY(-45%);
        //margin-top: -20%;
        z-index: 5;
        padding: 22px;
        box-sizing: border-box;

    }
    .leftBox{
        left: 20px;
        background: url("/src/assets/dwgk/leftBox.png") center center no-repeat;
        background-size: 100% 100%;

        .jvxx, .tdqkpm, .zcxmgl{
            width: 100%;
            height: 33%;
        }
        .zcxmgl, .jvxx{
            .content{
                width: 100%;
                height: 100%;
            }
        }
    }
    .rightBox{
        transition: 0.75s right ease-in-out;
        width: 23%;
        height: 87%;
        position: absolute;
        //top: 50%;
        //transform: translateY(-40%);
        //margin-top: -20%;
        z-index: 5;
        padding: 22px;
        box-sizing: border-box;
        //right: 20px;
        //background: url("/src/assets/dwgk/rightBox.png") center center no-repeat;
        background-image: url("/src/assets/details_bg.png");
        background-size: 100% 100%;
        .Details{
            width:100%;
            height: 100%;
            .closeDetails{
                position:absolute;
                cursor: pointer;
                left:-40px;
                top:50%;
                //transition: ;
                transform: translateY(-50%);
                width:50px;
                height: 173px;
                img{
                    height: 100%;
                    width: 100%;
                }
            }
        }
        .kptj{
            width: 100%;
            height: 30%;
            .main{
                width: 100%;
                height: 100%;
            }
        }
        .jdsl{
            width: 100%;
            height: 35%;
            .chat{
                width: 100%;
                height: 100%;
            }
        }
        .whtj{
            width: 100%;
            height: 35%;
            .chat{
                width: 100%;
                height: 100%;
            }
        }

        //.kptj{
        //
        //}
    }
    .loading{
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
        //z-index: 99;
        display: flex;
        flex-direction: row;
        justify-content: space-around;
        align-items: center;
        background: black;
    }

    .mainBox{
        width: 54%;
        height: fit-content;
        position: absolute;
        bottom: 10%;
        left: 50%;
        margin-left: -27%;
    }

    .leftbar {
        position: absolute;
        left: 25%;
        top: 20%;
        background: rgba(18, 70, 98, 0.9);
        //background: #fff;
        width: fit-content;
        height: fit-content;
        z-index: 4;
        cursor: pointer;
        .lt, .lb, .rt, .rb{
            position: absolute;
            width: 6px;
            height: 6px;
        }
        .lt{
            top: -1px;
            left: -1px;
            border-top: 1px solid #fff;
            border-left: 1px solid #fff;
        }
        .lb{
            bottom: -1px;
            left: -1px;
            border-bottom: 1px solid #fff;
            border-left: 1px solid #fff;
        }
        .rt{
            right: -1px;
            top: -1px;
            border-top: 1px solid #fff;
            border-right: 1px solid #fff;
        }
        .rb{
            bottom: 0;
            right: 0;
            border-bottom: 1px solid #fff;
            border-right: 1px solid #fff;
        }
        .action-button{
            width: fit-content;
            height: fit-content;
            padding: 0;
            display: block;
            font-size: 16px;
            background-color: transparent;
            color: #6e6e6e;
            text-align: center;
            .icon{
                width: 40px;
                height: 40px;
            }
        }
        .esri-icon-measure-line, .esri-icon-measure-area{
            &::before{
                content: '';
                width: 0;
                height: 0;
            }
        }
    }

    .itemlist{
        position: absolute;
        right: 25%;
        top: 20%;
    }


    .active{
        border: 1px solid #00a0ff;
    }
}
</style>
